package com.ruoyi.flow.advice;

import com.ruoyi.common.exception.base.BaseException;
import com.youlai.common.exception.BizException;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashSet;
import java.util.Set;

@Api(tags = "异常处理类")
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    /**
     * <p>处理常见通用异常</p>
     *
     * @param e 异常
     * @return 服务响应
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class})
    public ResponseEntity<Result<Void>> handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST, ResultCode.REQUEST_NOT_SUPPORTED_ERROR);
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            return getResponseEntity(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ResultCode.MEDIA_TYPE_NOT_SUPPORTED_ERROR);
        } else if (e instanceof MissingPathVariableException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST, ResultCode.MISSING_PATH_VARIABLE_ERROR);
        } else if (e instanceof MissingServletRequestParameterException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.MISSING_REQUEST_PARAM_ERROR);
        } else if (e instanceof TypeMismatchException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.TYPE_MISMATCH_ERROR);
        } else if (e instanceof HttpMessageNotReadableException) {
            return getResponseEntity(HttpStatus.BAD_REQUEST, ResultCode.HTTP_MESSAGE_NOT_READABLE_ERROR);
        } else if (e instanceof HttpMessageNotWritableException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.HTTP_MESSAGE_NOT_WRITABLE_ERROR);
        } else if (e instanceof HttpMediaTypeNotAcceptableException) {
            return getResponseEntity(HttpStatus.NOT_ACCEPTABLE, ResultCode.MEDIA_TYPE_NOT_ACCEPTABLE_ERROR);
        } else if (e instanceof ServletRequestBindingException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.REQUEST_BINDING_ERROR);
        } else if (e instanceof MissingServletRequestPartException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.MISSING_REQUEST_PART_ERROR);
        } else if (e instanceof AsyncRequestTimeoutException) {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.ASYNC_REQUEST_TIMEOUT_ERROR);
        } else {
            return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.SERVER_ERROR);
        }
    }

    /**
     * <p>处理数据绑定异常</p>
     *
     * @param e 数据绑定异常
     * @return 服务响应
     */
    @ExceptionHandler(BindException.class) public ResponseEntity<Result<Void>> handleBindingException(BindException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(getBindingResult(e.getBindingResult()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * <p>处理参数无效异常</p>
     *
     * @param e 参数无效异常
     * @return 服务响应
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<Result<Void>> handleArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(getBindingResult(e.getBindingResult()), HttpStatus.OK);
    }

    /**
     * <p>处理违反约束异常</p>
     *
     * @param e 违反约束异常
     * @return 服务响应
     */
    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseEntity<Result<Void>> handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        Result<Void> result = Result.failed(ResultCode.PARAMETER_VALID_ERROR);
        Set<String> messageSet = new HashSet<>();
        e.getConstraintViolations().forEach(action -> {
            messageSet.add(action.getMessage());
        });
        StringBuffer messageBuffer = new StringBuffer(result.getMsg());
        messageSet.forEach(message -> {
            messageBuffer.append(message).append(",");
        });
        result.setMsg(messageBuffer.substring(0, messageBuffer.length() - 1));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * <p>处理校验异常</p>
     *
     * @param e 校验异常
     * @return 服务响应
     */
    @ExceptionHandler({ValidationException.class}) public ResponseEntity<Result<Void>> handleValidationException(
            ValidationException e) {
        log.error(e.getMessage(), e);
        Result<Void> result = Result.failed(ResultCode.PARAMETER_VALID_ERROR);
        result.setMsg(result.getMsg() + e.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * <p>处理业务异常</p>
     *
     * @param e 业务异常
     * @return 服务响应
     */
    @ExceptionHandler(value = BizException.class)
    public ResponseEntity<Result<Void>> handleBusinessException(BizException e) {
        log.error(e.getMessage(), e);
        Result<Void> result = Result.failed(e);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * <p>自定义异常处理</p>
     *
     * @param e 自定义异常
     * @return 服务响应
     */
    @ExceptionHandler(value = BaseException.class) @ResponseBody
    public ResponseEntity<Result<Void>> handleBaseException(BaseException e) {
        log.error(e.getMessage(), e);
        return getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.SERVER_ERROR);
    }

    /**
     * <p>未知异常处理</p>
     *
     * @param e 异常
     * @return 服务响应
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Result<Void>> handleException(Exception e) {
        ResponseEntity<Result<Void>> responseEntity =
                getResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.SERVER_ERROR);
        log.error(e.getMessage(), e);
        return responseEntity;
    }

    /**
     * <p>构造异常返回实体</p>
     *
     * @param httpStatus http响应码
     * @param resultCode     服务返回码
     * @return Result<Void> 服务响应
     */
    private ResponseEntity<Result<Void>> getResponseEntity(HttpStatus httpStatus, ResultCode resultCode) {
        Result<Void> result = Result.failed(resultCode);
        return new ResponseEntity<>(result, httpStatus);
    }

    /**
     * <p>包装绑定异常结果</p>
     *
     * @param bindingResult 绑定结果
     * @return 服务响应
     */
    private Result<Void> getBindingResult(BindingResult bindingResult) {
        StringBuilder message = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            message.append(", ");
            if (error instanceof FieldError) {
                message.append(((FieldError) error).getField()).append(": ");
            }
            message.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }
        Result<Void> result = Result.failed(ResultCode.PARAM_ERROR);
        if (message.length() > 2) {
            result.setMsg(result.getMsg() + message.substring(2));
        }
        return result;
    }
}
